package org.yinxianren.www.study_02.study.netty.one;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SimpleChatClient {

    private final String host;        // IP
    private final int port;        // 端口

    public SimpleChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    // 配置并运行客户端
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();        // 客户端辅助启动类
            b.group(group)                                    // 客户端只需要一个用来接收并处理连接
                    .channel(NioSocketChannel.class)            // 设置如何接受连接
                    .handler(new SimpleChatClientInitializer());// 配置 channel
            // 连接服务器
            Channel channel = b.connect(host, port).sync().channel();
            // 读取控制台输入字符
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while(true) {
                // 每行成一帧输出，以"\r\n"结尾
                channel.writeAndFlush(in.readLine() + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();        // 输出异常
        } finally {
            group.shutdownGracefully();    // 关闭
        }
    }

    public static void main(String[] args) throws Exception {
        new SimpleChatClient("localhost", 8080).run();        // 启动客户端
    }
}


/**
 * 客户端处理类
 * 直接输出收到的消息
 */
class SimpleChatClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);    // 直接输出消息
    }

}



/**
 * 客户端配置初始化
 * 与服务端类似
 */
class SimpleChatClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 添加处理类
        // 使用'\r''\n'分割帧
        pipeline.addLast("framer",
                new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        // 解码、编码器
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        // 处理器
        pipeline.addLast("handler", new SimpleChatClientHandler());
    }

}